<template>
  <view class="search-page">
    <!-- 搜索框 -->
    <view class="search-header">
      <view class="search-input-wrap">
        <u-icon name="search" size="20" color="#666"></u-icon>
        <input 
          class="search-input" 
          type="text" 
          v-model="searchText"
          placeholder="搜索照片、相册" 
          placeholder-class="input-placeholder"
          @confirm="handleSearch"
        />
        <u-icon 
          v-if="searchText" 
          name="close" 
          size="20" 
          color="#999"
          @click="clearSearch"
        ></u-icon>
      </view>
      <text class="cancel-btn" @click="goBack">取消</text>
    </view>

    <!-- 搜索结果列表 -->
    <view class="search-content" v-if="searchText">
      <view v-if="loading" class="loading-container">
        <u-loading-icon mode="circle" size="36" color="#3a8838"></u-loading-icon>
        <text class="loading-text">搜索中...</text>
      </view>
      
      <template v-else>
        <view v-if="albumResults.length || photoResults.length" class="result-list">
          <!-- 相册结果 -->
          <view v-if="albumResults.length" class="result-section">
            <view class="section-title">相册</view>
            <view class="album-grid">
              <view 
                class="album-item" 
                v-for="(item, index) in albumResults" 
                :key="index"
                @click="handleItemClick(item)"
              >
                <image 
                  class="album-cover" 
                  :src="item.coverUrl"
                  mode="aspectFill"
                  @error="handleImageError"
                ></image>
                <view class="album-info">
                  <text class="album-title">{{item.title}}</text>
                  <text class="album-desc">{{item.description}}</text>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 照片结果 -->
          <view v-if="photoResults.length" class="result-section">
            <view class="section-title">照片</view>
            <view class="photo-grid">
              <view 
                class="photo-item" 
                v-for="(item, index) in photoResults" 
                :key="index"
                @click="handleItemClick(item)"
              >
                <image 
                  class="photo-image" 
                  :src="item.photoUrl"
                  mode="aspectFill"
                  @error="handleImageError"
                ></image>
                <view class="photo-info">
                  <text class="photo-title">{{item.title}}</text>
                  <text class="photo-desc">{{item.description}}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <view v-else class="empty-result">
          <u-empty mode="search" text="未找到相关结果"></u-empty>
        </view>
      </template>
    </view>
    
    <!-- 搜索历史 -->
    <view class="search-history" v-else>
      <view class="history-header">
        <text class="history-title">搜索历史</text>
        <u-icon name="trash" size="20" color="#999" @click="clearHistory"></u-icon>
      </view>
      <view class="history-list">
        <text 
          class="history-item" 
          v-for="(item, index) in searchHistory" 
          :key="index"
          @click="handleHistoryClick(item)"
        >{{item}}</text>
      </view>
    </view>
  </view>
</template>

<script>
import { search } from '@/api/search'
import { getImageBlob } from '@/utils/image'
import { formatDate } from '@/utils/date'

export default {
  data() {
    return {
      searchText: '',
      albumResults: [],
      photoResults: [],
      loading: false,
      searchHistory: []
    }
  },
  onLoad() {
    // 加载搜索历史
    this.loadSearchHistory()
  },
  methods: {
    // 加载搜索历史
    loadSearchHistory() {
      const history = uni.getStorageSync('searchHistory') || []
      this.searchHistory = history
    },
    
    // 保存搜索历史
    saveSearchHistory(keyword) {
      if (!keyword) return
      
      // 移除已存在的相同关键词
      this.searchHistory = this.searchHistory.filter(item => item !== keyword)
      
      // 添加到开头
      this.searchHistory.unshift(keyword)
      
      // 限制历史记录数量
      if (this.searchHistory.length > 10) {
        this.searchHistory = this.searchHistory.slice(0, 10)
      }
      
      // 保存到本地存储
      uni.setStorageSync('searchHistory', this.searchHistory)
    },
    
    // 清空搜索历史
    clearHistory() {
      uni.showModal({
        title: '提示',
        content: '确定要清空搜索历史吗？',
        success: (res) => {
          if (res.confirm) {
            this.searchHistory = []
            uni.removeStorageSync('searchHistory')
          }
        }
      })
    },
    
    // 处理搜索
    async handleSearch() {
      if (!this.searchText.trim()) return
      
      this.loading = true
      try {
        const res = await search(this.searchText)
        if (res.data) {
          // 分别处理相册和照片结果
          const albums = res.data.filter(item => item.sourceType === 'album').slice(0, 10)
          const photos = res.data.filter(item => item.sourceType === 'photo').slice(0, 10)
          
          // 处理相册图片
          this.albumResults = await Promise.all(albums.map(async item => {
            try {
              const coverUrl = item.coverPhotoPath ? await getImageBlob(item.coverPhotoPath) : ''
              return { ...item, coverUrl }
            } catch (error) {
              console.error('获取相册封面失败:', error)
              return { ...item, coverUrl: '' }
            }
          }))
          
          // 处理照片图片
          this.photoResults = await Promise.all(photos.map(async item => {
            try {
              const photoUrl = item.photoPath ? await getImageBlob(item.photoPath) : ''
              return { ...item, photoUrl }
            } catch (error) {
              console.error('获取照片失败:', error)
              return { ...item, photoUrl: '' }
            }
          }))
          
          // 保存搜索历史
          this.saveSearchHistory(this.searchText.trim())
        }
      } catch (error) {
        console.error('搜索失败:', error)
        uni.showToast({
          title: '搜索失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 清空搜索
    clearSearch() {
      this.searchText = ''
      this.albumResults = []
      this.photoResults = []
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 处理历史记录点击
    handleHistoryClick(keyword) {
      this.searchText = keyword
      this.handleSearch()
    },
    
    // 处理搜索结果点击
    handleItemClick(item) {
      if (item.sourceType === 'album') {
        uni.navigateTo({
          url: `/pages/album/detail?id=${item.id}`
        })
      } else {
        uni.navigateTo({
          url: `/pages/photo/detail?id=${item.id}`
        })
      }
    },
    
    // 处理图片加载错误
    handleImageError(e) {
      console.error('图片加载失败:', e)
      e.target.src = '/static/images/default-cover.png'
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''
      return formatDate(new Date(dateStr), 'yyyy-MM-dd')
    }
  }
}
</script>

<style>
.search-page {
  min-height: 100vh;
  background-color: #f8f8f8;
}

.search-header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 100;
}

.search-input-wrap {
  flex: 1;
  height: 72rpx;
  background-color: #f5f5f5;
  border-radius: 36rpx;
  display: flex;
  align-items: center;
  padding: 0 24rpx;
  margin-right: 20rpx;
}

.search-input {
  flex: 1;
  height: 100%;
  font-size: 28rpx;
  margin: 0 16rpx;
}

.input-placeholder {
  color: #999;
}

.cancel-btn {
  font-size: 28rpx;
  color: #666;
}

.search-content {
  padding: 20rpx;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0;
}

.loading-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #666;
}

.result-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.result-section {
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  padding-left: 20rpx;
  position: relative;
}

.section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 8rpx;
  height: 30rpx;
  background-color: #3a8838;
  border-radius: 4rpx;
}

.album-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  padding: 0 20rpx;
}

.album-item {
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.album-cover {
  width: 100%;
  height: 300rpx;
  background-color: #f0f0f0;
}

.album-info {
  padding: 16rpx;
}

.album-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 8rpx;
  display: block;
}

.album-desc {
  font-size: 24rpx;
  color: #666;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  padding: 0 20rpx;
}

.photo-item {
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.photo-image {
  width: 100%;
  height: 300rpx;
  background-color: #f0f0f0;
}

.photo-info {
  padding: 16rpx;
}

.photo-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 8rpx;
  display: block;
}

.photo-desc {
  font-size: 24rpx;
  color: #666;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.empty-result {
  padding: 100rpx 0;
}

.search-history {
  padding: 30rpx;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.history-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.history-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.history-item {
  padding: 12rpx 24rpx;
  background-color: #f5f5f5;
  border-radius: 30rpx;
  font-size: 26rpx;
  color: #666;
}
</style> 